package ac.beiwo.baas.file.service;

import ac.beiwo.baas.common.entity.SimpleCode;
import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.file.entity.BaasFile;
import ac.beiwo.baas.file.entity.FileStoragePlatform;
import ac.beiwo.baas.file.handler.IFileHandler;
import ac.beiwo.baas.file.handler.impl.QiniuFileHandler;
import ac.beiwo.baas.object.entity.BaasObject;
import ac.beiwo.baas.object.service.ObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Staryet on 15/8/26.
 */
@Service
public class FileService {

    public static String FILE_CLASS_NAME = "_File";
    @Autowired
    private ObjectService objectService;
    @Autowired
    private QiniuFileHandler qiniuFileHandler;

    public Map<String, Object> getToken(FileStoragePlatform plat, String fileName) throws SimpleError {
        return getFileHandler(plat).getToken(fileName);
    }

    public BaasFile callback(FileStoragePlatform plat, String body, HttpServletRequest request) throws SimpleError {
        return getFileHandler(plat).callback(body, request);
    }

    public BaasFile getFile(String id) throws SimpleError {
        BaasObject object = objectService.get(FILE_CLASS_NAME, id);
        if (object == null) {
            return null;
        } else {
            return new BaasFile(object);
        }
    }

    public void saveFile(BaasFile file) throws SimpleError {
        //禁止设置ACL字段
        file.remove("acl");
        String id = objectService.insert(FILE_CLASS_NAME, file, null, true);
        file.put("id", "id");
    }

    private IFileHandler getFileHandler(FileStoragePlatform plat) throws SimpleError {
        IFileHandler handler = null;
        switch (plat) {
            case Qiniu:
                handler = qiniuFileHandler;
                break;
            case Upyun:
                break;
            default:
                break;
        }
        if (handler == null) {
            throw new SimpleError(SimpleCode.FILE_NO_HANDLER);
        }
        return handler;
    }

}
